<template>
    <view class="abslrtb flex-column a-center wrap">
        <view style="height: 140rpx;">
            <BackNav title="登录" bgColor="#fcfcfc" :show-back="false" />
        </view>
        <view class="topbox flex-column aj-center">
            <u-image class="logoimg" src="/static/logo.png" mode=""></u-image>
        </view>
        <view class="flex tabs mb30">
            <view @click="tab(0)" class="flex-1 flex aj-center" :class="tabIndex == 0 && 'active'">
                <text class="fs30 fw600 " :class="tabIndex == 0 && 'curtext'">教师登录</text>
            </view>
            <view @click="tab(1)" class="flex-1 flex aj-center" :class="tabIndex == 1 && 'active'">
                <text class="fs30 fw600 " :class="tabIndex == 1 && 'curtext'">学生登录</text>
            </view>
        </view>
        <!-- <view class="switchCon">
            <text style="color: #7B8DF9;">教师登录：</text>
            <u-switch v-model="isTeacher" size="30" active-color="#7B8DF9" inactive-color="#DCDCDC"></u-switch>
        </view> -->
        <view class="form" v-if="isPasswordLogin" style="margin-top: 20rpx;">
            <view class="flex a-center form-item">
                <view class="label">
                    <text>账号</text>
                </view>
                <image class="label_icon" src="/static/images/icon_user.png" mode=""></image>
                <view class="label_fgs"></view>
                <view class="flex-1">
                    <input placeholder-class="placeholder" class="qui-input" type="text" v-model="userName"
                        placeholder="请输入账号" />
                </view>
            </view>
            <view class="flex a-center form-item">
                <view class="label">
                    <text>密码</text>
                </view>
                <image class="label_icon" src="/static/images/icon_pw.png" mode=""></image>
                <view class="label_fgs"></view>
                <view class="flex-1">
                    <input placeholder-class="placeholder" :password="isPassword" class="qui-input" type="text"
                        v-model="password" placeholder="请输入密码" />
                </view>
            </view>
        </view>

        <view class="form" v-if="!isPasswordLogin" style="margin-top: 20rpx;">
            <view class="flex a-center form-item">
                <view class="label">
                    <text>手机号</text>
                </view>
                <image class="label_icon" src="/static/images/icon_phone.png" mode=""></image>
                <view class="label_fgs"></view>
                <view class="flex-1">
                    <input placeholder-class="placeholder" class="qui-input" type="text" v-model="mobile"
                        placeholder="请输入手机号" />
                </view>
            </view>
            <view class="flex a-center form-item">
                <view class="label">
                    <text>验证码</text>
                </view>
                <image class="label_icon" src="/static/images/icon_code.png" mode=""></image>
                <view class="label_fgs"></view>
                <view class="flex-1">
                    <input placeholder-class="placeholder" class="qui-input" type="text" v-model="code"
                        placeholder="请输入验证码" maxlength="6" />
                </view>
                <view>
                    <text v-if="getCodeTime == 0" style="opacity: 0.8;" class="yzm fs28 ptb20 main-color"
                        @click="getCode">获取验证码</text>
                    <view v-else><text style="font-size: 20px;color:#0A84FF">{{ getCodeTime }}</text></view>
                </view>
            </view>
        </view>

        <view class="btns">
            <view class="qbtn" @click="login">
                <text class="btn-text-color fs30">登录</text>
            </view>
            <!-- <view class="ql-btn" @click="qlLogin">
				<image style="width:64rpx;height: 64rpx;" src="/static/img/qinglu.png"></image><text style="color:#00FFFF">青鹿登录</text>
			</view> -->
            <view class="flex ptb30 mlr20 space-between">
                <view @click="goRegister" class="">
                    <text class="fs26 nav-text-color underline">激活码注册</text>
                </view>
                <view class="" @click="isPasswordLogin = !isPasswordLogin">
                    <text class="fs26 nav-text-color underline">{{ isPasswordLogin ? '使用验证码登录' : '使用密码登录' }}</text>
                </view>
            </view>

        </view>
        <view class="user-protocal">
            <checkbox-group v-model="checkboxValues" @change="onUserProtocalChange">
                <checkbox value="userProtocal" />
            </checkbox-group>已阅读并同意
            <navigator url="../Mine/UserProtocal/UserProtocal">
                <text style="color:royalblue">《用户隐私协议》</text>
            </navigator>
        </view>
    </view>
</template>

<script setup lang="ts">
import uniReq from '@/api/uniReq';
import BackNav from '@/components/backNav/backNav.vue';
import { setToken } from '@/utils/auth';
import { ref, computed } from 'vue'

// 响应式数据
const tabIndex = ref(0); // 当前选中的选项卡索引
const userName = ref(''); // 账号
const password = ref(''); // 密码
const mobile = ref(''); // 手机号
const code = ref(''); // 验证码
const isPassword = ref(true); // 是否显示密码
const getCodeTime = ref(0); // 获取验证码倒计时
const userProtocalCheck = ref(false); // 用户隐私协议是否勾选
const checkboxValues = ref([]); // checkbox-group的值数组
let countdownTimer: any = null; // 倒计时定时器

const isTeacher = ref(false); // 是否教师登录

const isPasswordLogin = ref(true); // 是否密码登录

// 选项卡切换
const tab = (index: number) => {
    tabIndex.value = index;
}

// 获取验证码
const getCode = () => {
    if (!mobile.value) {
        uni.showToast({
            title: '请输入手机号',
            icon: 'none'
        })
        return;
    }

    // 简单的手机号格式验证
    const mobileRegex = /^1[3-9]\d{9}$/;
    if (!mobileRegex.test(mobile.value)) {
        uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none'
        })
        return;
    }

    // 开始倒计时
    getCodeTime.value = 60;
    countdownTimer = setInterval(() => {
        getCodeTime.value--;
        if (getCodeTime.value <= 0) {
            clearInterval(countdownTimer);
            countdownTimer = null;
        }
    }, 1000);

    // 模拟发送验证码（静态演示）
    uni.showToast({
        title: '验证码已发送',
        icon: 'success'
    })

    // 这里可以添加实际的验证码发送逻辑
    console.log('发送验证码到手机:', mobile.value);
}

// 倒计时结束
const endCounter = () => {
    getCodeTime.value = 0;
    if (countdownTimer) {
        clearInterval(countdownTimer);
        countdownTimer = null;
    }
}

// 用户协议勾选状态改变 - 修复后的实现
const onUserProtocalChange = (e: any) => {
    console.log('勾选状态改变:', e);
    const values = e.detail.value || [];
    userProtocalCheck.value = values.includes('userProtocal');
    console.log('协议勾选状态:', userProtocalCheck.value);
}

// 表单验证
const validateForm = () => {
    if (isPasswordLogin.value) {
        // 账号登录验证
        if (!userName.value.trim()) {
            uni.showToast({
                title: '请输入账号',
                icon: 'none'
            })
            return false;
        }
        if (!password.value.trim()) {
            uni.showToast({
                title: '请输入密码',
                icon: 'none'
            })
            return false;
        }
        if (password.value.length < 6) {
            uni.showToast({
                title: '密码长度不能少于6位',
                icon: 'none'
            })
            return false;
        }
    } else {
        // 手机登录验证
        if (!mobile.value.trim()) {
            uni.showToast({
                title: '请输入手机号',
                icon: 'none'
            })
            return false;
        }
        const mobileRegex = /^1[3-9]\d{9}$/;
        if (!mobileRegex.test(mobile.value)) {
            uni.showToast({
                title: '请输入正确的手机号',
                icon: 'none'
            })
            return false;
        }
        if (!code.value.trim()) {
            uni.showToast({
                title: '请输入验证码',
                icon: 'none'
            })
            return false;
        }
        if (code.value.length !== 6) {
            uni.showToast({
                title: '验证码应为6位数字',
                icon: 'none'
            })
            return false;
        }
    }
    return true;
}

// 登录处理
const login = () => {
    // 检查用户协议
    if (!userProtocalCheck.value) {
        uni.showToast({
            title: '请先同意用户隐私协议',
            icon: 'none'
        })
        return;
    }

    // 表单验证
    if (!validateForm()) {
        return;
    }

    // 显示加载中
    uni.showLoading({
        title: '登录中...'
    })
    uni.hideLoading();
    if (tabIndex.value === 0) {
        uniReq({
            url: '/auth/teacher-login?phone=' + userName.value + '&password=' + password.value,
            method: 'POST',
            // data: {
            //     phone: userName.value,
            //     password: password.value
            // }
        }).then(res => {
            if (res.status === 200) {
                uni.showToast({
                    title: '教师登录成功',
                    icon: 'success'
                })
                setToken(res.data.currentToken);
                // uni.setStorageSync('userType', res.data.userType);
                // uni.setStorageSync('userId', res.data.userId);
                uni.setStorageSync('userInfo', res.data);
                // 跳转到首页或其他页面
                uni.switchTab({
                    url: '/pages/index/index'
                })
            } else {
                uni.showToast({
                    title: res.message || '登录失败，请稍后重试',
                    icon: 'none'
                })
            }
        })
    } else {
        uniReq({
            url: '/auth/student-login?phone=' + userName.value + '&password=' + password.value,
            method: 'POST',
            // data: {
            //     phone: userName.value,
            //     password: password.value
            // }
        }).then(res => {
            if (res.status === 200) {
                uni.showToast({
                    title: '学生登录成功',
                    icon: 'success'
                })
                setToken(res.data.currentToken);
                // uni.setStorageSync('userType', res.data.userType);
                // uni.setStorageSync('userId', res.data.userId);
                // uni.setStorageSync('gradeId', res.data.gradeId);
                uni.setStorageSync('userInfo', res.data);
                // 跳转到首页或其他页面
                uni.switchTab({
                    url: '/pages/index/index'
                })
            } else {
                uni.showToast({
                    title: res.message || '登录失败，请稍后重试',
                    icon: 'none'
                })
            }
        })
    }
}

// 页面卸载时清理定时器
onUnmounted(() => {
    if (countdownTimer) {
        clearInterval(countdownTimer);
        countdownTimer = null;
    }
})

// 其他功能函数（可根据需要添加）
const goRegister = () => {
    uni.navigateTo({
        url: '/pages/login/firstLogin'
    })
}

const goForget = () => {
    uni.navigateTo({
        url: '/pages/login/forget'
    })
}

// 切换密码显示状态
const togglePassword = () => {
    isPassword.value = !isPassword.value;
}
</script>


<style scoped lang="scss">
@import url("./style/qui_weex.scss");
@import url("./style/skin06.scss");

.user-protocal {
    width: 100%;
    display: flex;
    justify-content: center;
    position: fixed;
    bottom: 200rpx;
}

.switchCon {
    width: 100%;
    padding: 0 60rpx;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-top: 20rpx;
}


.ql-btn {
    width: 640rpx;
    height: 90rpx;
    border-radius: 50rpx;
    border: solid 1rpx #00FFFF;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #FFFFFF;
    margin-top: 260rpx;
}
</style>